﻿using System.Collections.Generic;

using Db4objects.Db4o;


namespace DataAccess
{

    /// <summary>
    /// Query by example class.
    /// </summary>
    class QueryByExampleAction<GenericType> : IQueryAction<GenericType>
                                where GenericType : class
    {

        /// <summary>
        /// The object to be queried by (example). 
        /// </summary>
        private GenericType queryObject;

        /// <summary>
        /// The depth of the query in the objects' graph.
        /// </summary>
        private int queryDepth;


        /// <summary>
        /// QueryByExampleAction constructor.
        /// </summary>
        /// <param name="queryObject">The object to be queried by (example)</param>
        /// <param name="queryDepth">The depth of the query in the objects' graph</param>
        public QueryByExampleAction(GenericType queryObject, int queryDepth)
        {
            this.queryObject = queryObject;
            this.queryDepth = queryDepth;
        }


        /// <summary>
        /// Performs a query for data against the database.
        /// </summary>
        /// <param name="db">The database handle</param>
        /// <returns>The collection of objects retrieved by the query</returns>
        public IList<GenericType> PerformQuery(IObjectContainer db)
        {
            IList<GenericType> resultObjects = new List<GenericType>();

            IObjectSet objectSet = db.QueryByExample(queryObject);

            while (objectSet.HasNext() == true)
            {
                object currentObject = objectSet.Next();
                db.Activate(currentObject, queryDepth);

                resultObjects.Add((GenericType)currentObject);
            }

            return resultObjects;
        }

    }

}

